package com.qf.sl.youshare.tasks;

import android.os.AsyncTask;
import com.qf.sl.youshare.Constants;
import com.qf.sl.youshare.model.GoodsCart;
import com.qf.sl.youshare.utils.HttpTools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/25.
 * 20:19
 */
public class GoodsCartTask extends AsyncTask<String, Integer, JSONObject> {

    private TaskProcessor processor;

    public GoodsCartTask(TaskProcessor processor) {
        this.processor = processor;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        JSONObject ret = null;

        String userId = null;

        if (params != null && params.length > 0) {
            userId = params[0];
        }

        String url = null;
        if (userId != null) {
            url = Constants.CART_GET_URL + "&userid=" + userId;
        }else {
            url = Constants.CART_GET_URL;
        }

        byte[] bytes = HttpTools.get(url);

        try {
            String string = new String(bytes, "UTF-8");
            ret = new JSONObject(string);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

//        try {
//            String string = new String(bytes, "UTF-8");
//            JSONObject object = new JSONObject(string);
//            int code = object.getInt("code");
//            if (code == 1){
//                JSONObject msg = object.getJSONObject("msg");
//                JSONObject data = msg.getJSONObject("data");
//                JSONArray goods_list = data.getJSONArray("goods_list");
//                for (int i = 0; i < goods_list.length(); i++) {
//                    JSONObject listObject = goods_list.getJSONObject(i);
//                    GoodsCart cart = new GoodsCart();
//                    cart.parseJSON(listObject);
//                }
//            }
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        return ret;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        if (processor != null) {
            processor.processResult(jsonObject);
        };
    }
}
